package com.gc.ykqx.service.presenter;


import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.gc.ykqx.service.entity.Warn;
import com.gc.ykqx.service.manager.DataManager;
import com.gc.ykqx.service.view.View;
import com.gc.ykqx.service.view.WarnView;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by wsd on 2017/9/30.
 */

public class WarnPresenter implements Presenter {
    private DataManager manager;
    private CompositeSubscription mCompositeSubscription;
    private Context mContext;
    private WarnView mWarnView;
    private Warn mWarn;

    public WarnPresenter(Context context) {
        this.mContext = context;
    }

    @Override
    public void onCreate() {
        manager = new DataManager(mContext);
        mCompositeSubscription = new CompositeSubscription();

    }

    @Override
    public void onStart() {

    }

    @Override
    public void onStop() {
        if (mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }

    }

    @Override
    public void pause() {

    }

    @Override
    public void attachView(View view) {
        mWarnView = (WarnView) view;

    }

    @Override
    public void attachIncomingIntent(Intent intent) {

    }

    public void getWarn() {
        mCompositeSubscription.add(manager.getWarn()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Warn>() {
                    @Override
                    public void onCompleted() {
                        if (mWarn != null) {
                            mWarnView.onSuccess(mWarn);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(Warn warn) {
                        mWarn = warn;
                    }
                }));
    }
}
